package edu.cuit.canary.commons.oss.service.support;

import edu.cuit.canary.commons.oss.config.MinioConfigProperties;
import edu.cuit.canary.commons.oss.service.FileService;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@Slf4j
public class FileServiceBean implements FileService {
    @Resource private MinioClient client;
    @Resource private MinioConfigProperties properties;

    @Override
    public String uploadFile(String fileName, String contentType, InputStream input) {
        try {
            var path = buildFilePath(fileName);
            var parameter  = PutObjectArgs.builder()
                    .bucket(properties.getBucket()) //bucket
                    .contentType(contentType) //文件类型
                    .object(path) //文件名称
                    .stream(input, input.available(), -1)
                    .build();
            client.putObject(parameter);
            return properties.getEndpoint() + "/" + properties.getBucket() + "/" + buildFilePath(fileName);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            //throw new RuntimeException(e);
            return null;
        }
    }


    @Override
    public String uploadImageFile(String fileName, String contentType, InputStream input) {
        if(!contentType.startsWith("image"))
            throw new RuntimeException("上传的文件非图片:" + contentType);
        return uploadFile(fileName,contentType, input);
    }

    @Override
    public String uploadHtmlFile(String fileName, InputStream input) {
        if(!fileName.endsWith(".html") || !fileName.endsWith(".html"))
            throw new RuntimeException("上传的文件非html:" + fileName);
        return uploadFile(fileName,"text/html", input);
    }

    @Override
    public void delete(String path) {
        try{
            var parameter = RemoveObjectArgs.builder()
                    .bucket(properties.getBucket())
                    .object(path)
                    .build();
            client.removeObject(parameter);
        }catch (Exception e){
            log.error(e.getMessage(), e);
        }
    }

    @Override
    public byte[] downLoadFile(String path) {
        try {
            var params = GetObjectArgs.builder()
                    .bucket(properties.getBucket())
                    .object(path)
                    .build();
            return client.getObject(params).readAllBytes();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            //throw new RuntimeException(e);
            return null;
        }
    }

    /**
     * 构建文件路径 real-path/yyyy/MM/dd/filename: admin/2024/08/28/sufei.jpg
     * @param filename 文件名
     * @return 文件路径
     */
    private String buildFilePath(String filename){
        var sb = new StringBuilder();
        var date = DateTimeFormatter.ofPattern("yyyy/MM/dd").format(LocalDate.now());
        if(StringUtils.hasLength(properties.getReadPath()))
           sb.append(properties.getReadPath()).append("/");
        sb.append(date).append("/").append(filename);

        return sb.toString();
    }
}
